<script setup lang="ts">
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import { exportProduct, importProduct, useDelProduct, useGetProductPage, usePutawayProduct } from '@fl/api/supplier'
import { SearchForm, SearchTable } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { cloneDeep } from 'lodash-es'

import { AUDIT_VALUE, MALL_TYPE, PRODUCT_STATUS_VALUE } from './constant'

const router = useRouter()
const tableRef = ref()
const { createConfirmModal, createMessage } = useMessage()
const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))

type IState = {
    isShow?: number | string
    productModel?: string
    productName?: string
    productNo?: string
    productSource?: string
    productStatus?: number | string
}

const initialState: IState = {
    isShow: '',
    productModel: '',
    productName: '',
    productNo: '',
    productSource: '',
    productStatus: '',
}
const state = ref(cloneDeep(initialState))

const params = computed(() => ({
    page: tablePage.value.currentPage,
    size: tablePage.value.pageSize,
    ...state.value,
}))

const { data: tableData, isLoading } = useGetProductPage(params)
const { mutate: delProductMutate } = useDelProduct()
const { mutate: putawayProductMutate } = usePutawayProduct()

const records = ref()
watchEffect(() => {
    if (tableData.value) {
        records.value = cloneDeep(tableData.value.records)
        tablePage.value.total = tableData.value.total ?? 0
    }
})

const columns: PlusColumn[] = [
    {
        label: '状态',
        options: [
            {
                label: '未上架',
                value: '0',
            },
            {
                label: '已上架',
                value: '1',
            },
        ],
        prop: 'productStatus',
        valueType: 'select',
    },
    {
        label: '产品名称',
        prop: 'productName',
    },
    {
        label: '产品编码',
        prop: 'productNo',
    },
    {
        label: '来源',
        options: [
            {
                label: '集采商城',
                value: '0',
            },
            {
                label: '采筑商城',
                value: '1',
            },
        ],
        prop: 'productSource',
        valueType: 'select',
    },
    {
        label: '产品型号',
        prop: 'productModel',
    },
    {
        label: '是否上架展示',
        options: [
            {
                label: '展示',
                value: '1',
            },
            {
                label: '不展示',
                value: '0',
            },
        ],
        prop: 'isShow',
        valueType: 'select',
    },
    {
        label: '审核状态',
        options: [
            {
                label: '待审核',
                value: 1,
            },
            {
                label: '审核成功',
                value: 2,
            },
            {
                label: '审核失败',
                value: 3,
            },
        ],
        prop: 'productAuditStatus',
        valueType: 'select',
    },
]

const AUDIT_STATUS = {
    0: {
        label: '--',
    },
    1: {
        bg: 'bg-stone-400',
        label: '待审核',
    },
    2: {
        bg: 'bg-green-300',
        label: '审核通过',
    },
    3: {
        bg: 'bg-stone-300',
        label: '审核未通过',
    },
}

const STATUS_DICT = {
    0: {
        batchTooltipLabel: '是否批量下架这些产品',
        bg: 'bg-stone-300',
        label: '未上架',
        msg: '操作成功',
        status: 1,
        tooltipLabel: '是否上架该产品',
    },
    1: {
        batchTooltipLabel: '是否批量上架这些产品',
        bg: 'bg-green-300',
        label: '已上架',
        msg: '下架成功',
        status: 0,
        tooltipLabel: '是否下架该产品',
    },
}

const gridOptions = reactive<VxeGridProps<any>>({
    align: 'center',
    columnConfig: {
        resizable: true,
    },
    columns: [
        { type: 'checkbox', width: 50 },
        { field: 'productNo', title: '产品编码' },
        { field: 'productName', title: '产品名称' },
        { field: 'brandName', title: '产品品牌' },
        { field: 'categoryPath', title: '产品类目' },
        { field: 'productModel', title: '型号' },
        { field: 'productPrice', slots: { default: 'productPrice' }, title: '价格' },
        { field: 'productAgreementsCount', title: '相关协议(个)' },
        { field: 'productSource', slots: { default: 'productSource' }, title: '来源' },
        { field: 'productSalesVolume', title: '销量' },
        { field: 'createBy', title: '创建人' },
        { field: 'productStatus', slots: { default: 'productStatus' }, title: '产品状态' },
        { field: 'productAuditStatus', slots: { default: 'productAuditStatus' }, title: '审核状态' },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 200 },
    ],
    data: [],
    height: 550,
    toolbarConfig: {
        slots: {
            buttons: 'toolbar_buttons',
        },
    },
})

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

function search(values: any) {
    tablePage.value = cloneDeep(initialPage)
    state.value = { ...state.value, ...values }
}

function reset() {
    state.value = { ...initialState }
    tablePage.value = cloneDeep(initialPage)
}

function addForm() {
    router.push('/supplier-pages/product-management/add')
}

function detail(id: string) {
    router.push({
        path: '/supplier-pages/product-management/detail',
        query: {
            id,
        },
    })
}

function viewHandle(id: string) {
    router.push({
        path: '/product-info',
        query: {
            id,
        },
    })
}

function logHandle(id: string) {
    router.push({ path: `/supplier-pages/product-management/${id}/log` })
}

function edit(id: string) {
    router.push({
        path: '/supplier-pages/product-management/add',
        query: {
            id,
        },
    })
}

function isProductAudit(row: any) {
    return row.some(item => item.productAuditStatus === AUDIT_VALUE.Audit)
}

function isPutway(row: any) {
    return row.some(item => item.productAuditStatus === AUDIT_VALUE.Putway)
}

function batchDel() {
    const $table = tableRef.value?.tableInstance
    if ($table) {
        const selectRecords = $table.getCheckboxRecords()
        if (isProductAudit(selectRecords)) {
            createMessage.warning('存在商品正在审核中，请勿进行此操作！')
            return
        }
        if (isPutway(selectRecords)) {
            createMessage.warning('存在商品已上架，请勿进行此操作！')
            return
        }
        const ids = selectRecords.map(item => item.id).join(',')
        console.log(selectRecords, 'selectRecords')
        if (selectRecords.length) {
            createConfirmModal({ content: '是否确认删除？', onError: () => {
                console.log('操作取消！')
            }, onSuccess: () => {
                delProductMutate(ids, {
                    onSuccess: () => {
                        createMessage.success('删除成功')
                    },
                })
            } })
        }
        else {
            createMessage.warning('请至少选择一条数据')
        }
    }
}

function putaway(row: any) {
    const tip = STATUS_DICT[row.productStatus].tooltipLabel
    createConfirmModal({ content: tip, onError: () => {
        console.log('操作取消！')
    }, onSuccess: () => {
        putawayProductMutate({
            productIds: [row.id],
            status: Number(STATUS_DICT[row.productStatus].status),
        }, {
            onSuccess: () => {
                const msg = STATUS_DICT[row.productStatus].msg
                ElMessage.success(msg)
            },
        })
    } })
}

function checkProductStatus(type: number, row: any) {
    if (type === PRODUCT_STATUS_VALUE.Putway) {
        if (row.some(item => item.productStatus === PRODUCT_STATUS_VALUE.Putway)) {
            createMessage.warning('存在已上架商品，请重新选择！')
            return true
        }
        else {
            return false
        }
    }
    else {
        if (row.some(item => item.productStatus === PRODUCT_STATUS_VALUE.Putoff)) {
            createMessage.warning('存在未上架商品，请重新选择！')
            return true
        }
        else {
            return false
        }
    }
}

function batchPutaway(type: number) {
    const $table = tableRef.value?.tableInstance
    if ($table) {
        const selectRecords = $table.getCheckboxRecords()
        if (isProductAudit(selectRecords)) {
            createMessage.warning('存在商品正在审核中，请勿进行此操作！')
            return
        }
        if (checkProductStatus(type, selectRecords))
            return
        if (selectRecords.length) {
            const ids = selectRecords.map(item => item.id)
            const tip = STATUS_DICT[type].batchTooltipLabel
            createConfirmModal({ content: tip, onError: () => {
                console.log('操作取消！')
            }, onSuccess: () => {
                putawayProductMutate({ productIds: ids, status: type }, {
                    onSuccess: () => {
                        createMessage.success('操作成功')
                    },
                })
            } })
        }
        else {
            createMessage.warning('请至少选择一条数据')
        }
    }
}

async function exportProductList() {
    const params = {
        ...state.value,
    }
    try {
        await exportProduct('产品列表.xls', params)
        createMessage.success('导出成功')
    }
    catch (error) {
        createMessage.error('导出失败')
    }
}

// function handleSuccess(res: any) {
//     console.log('🚀 ~ handleSuccess ~ res:', res)
// }

// function beforeUpload(file: any) {
//     const fileType = ['xlsx', 'xls']
//     const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
//     const isFile = fileType.includes(suffix)
//     if (!isFile) {
//         createMessage.error('上传文件只能是xlsx、xls格式!')
//     }
//     return isFile
// }

// function requestClick(params: any) {
//     console.log('🚀 ~ requestClick ~ options:', params)
//     const file = params.file
//     return uploadFile(file)
// }

// async function uploadFile(file) {
//     const formData = new FormData()
//     formData.append('file', file)
//     const res = await importProduct(formData)
//     console.log(res, 'res')
//     createMessage.error('导入成功')
// }
</script>

<template>
    <div class="mb-20">
        <ElCard shadow="never">
            <SearchForm v-bind="state"
                        :columns="columns"
                        submit-text="查询"
                        @submit="search"
                        @reset="reset"
            />
        </ElCard>
    </div>

    <ElCard shadow="never">
        <SearchTable ref="tableRef"
                     v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isLoading"
                     :data="records"
                     row-class-name="table-row-style"
                     @page-change="handlePageChange"
        >
            <template #toolbar_buttons>
                <el-space class="mb-12">
                    <el-button type="primary"
                               @click="addForm"
                    >
                        <div class="i-ic:baseline-add size-16" />
                        新增
                    </el-button>

                    <!-- <el-upload class="upload-demo mr10"
                               action="#"
                               :show-file-list="false"
                               :http-request="requestClick"
                               :on-success="handleSuccess"
                               :before-upload="beforeUpload"
                    >
                        <el-button size="middle">
                            批量导入
                        </el-button>
                    </el-upload> -->

                    <el-dropdown>
                        <el-button>
                            批量操作 <div class="i-formkit:down size-16" />
                        </el-button>

                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="batchPutaway(PRODUCT_STATUS_VALUE.Putway)">
                                    批量上架
                                </el-dropdown-item>

                                <el-dropdown-item @click="batchPutaway(PRODUCT_STATUS_VALUE.Putoff)">
                                    批量下架
                                </el-dropdown-item>

                                <el-dropdown-item @click="batchDel">
                                    批量删除
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>

                    <el-button @click="exportProductList">
                        导出清单
                    </el-button>
                </el-space>
            </template>

            <template #productPrice="{ row }">
                {{ row.productPrice ? row.productPrice : '询价' }}
            </template>

            <template #productSource="{ row }">
                {{ MALL_TYPE[row.productSource] }}
            </template>

            <template #productStatus="{ row }">
                <span class="inline-block rounded-full h-8 w-8"
                      :class="STATUS_DICT[row.productStatus].bg"
                />
                {{ STATUS_DICT[row.productStatus].label }}
            </template>

            <template #productAuditStatus="{ row }">
                <span class="inline-block rounded-full h-8 w-8"
                      :class="AUDIT_STATUS[row.productAuditStatus]?.bg"
                />
                {{ AUDIT_STATUS[row.productAuditStatus]?.label }}
            </template>

            <template #operate="{ row }">
                <ElSpace class="red">
                    <span class="text-#409EFF cursor-pointer"
                          @click="viewHandle(row.productNo)"
                    >
                        预览
                    </span>

                    <span class="text-#409EFF cursor-pointer"
                          @click="putaway(row)"
                    >
                        {{ (row.productStatus === PRODUCT_STATUS_VALUE.Putway && row.productAuditStatus !== AUDIT_VALUE.Audit) ? '下架' : (row.productStatus === PRODUCT_STATUS_VALUE.Putoff && row.productAuditStatus !== AUDIT_VALUE.Audit) ? '上架' : '' }}
                    </span>

                    <span v-if="row.productStatus === PRODUCT_STATUS_VALUE.Putway"
                          class="text-#409EFF cursor-pointer"
                          @click="detail(row.id)"
                    >
                        详情修订
                    </span>

                    <span v-if="row.productStatus === PRODUCT_STATUS_VALUE.Putoff && row.productAuditStatus !== AUDIT_VALUE.Audit"
                          class="text-#409EFF cursor-pointer"
                          @click="edit(row.id)"
                    >
                        编辑
                    </span>

                    <span class="text-#409EFF cursor-pointer"
                          @click="logHandle(row.id)"
                    >
                        日志
                    </span>
                </ElSpace>
            </template>
        </SearchTable>
    </ElCard>
</template>
